package edu.pku.sei.transformation.editor.controller.commands.node;

import org.eclipse.draw2d.geometry.Rectangle;

import edu.pku.sei.modeler.model.structure.MetaNode;

public class NestedNodeCreateCommand extends NestedCommand {
	private MetaNode fatherNode;
	private MetaNode childNode;
	private Rectangle constraint;
	private int index = -1;

	public NestedNodeCreateCommand(MetaNode childNode, MetaNode fatherNode,
			Rectangle constraint) {
		this.childNode = childNode;
		this.fatherNode = fatherNode;
		this.constraint = constraint;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	@Override
	public boolean canExecute() {
		if (this.fatherNode != null && this.childNode != null
				&& this.constraint != null) {
			return super.canExecute();
		} else {
			return false;
		}
	}

	@Override
	public void execute() {
		updateBounds();
		this.childNode.setContainer(this.fatherNode);
		childNode.setDiagram(fatherNode.getDiagram());
		childNode.setContainer(this.fatherNode);
		if (index < 0 || index > this.fatherNode.getSubNodes().size())
			this.fatherNode.getSubNodes().add(this.childNode);
		else
			this.fatherNode.getSubNodes().add(index, this.childNode);
		if (modelCmd != null) {
			modelCmd.execute();
		}
	}

	private void updateBounds() {
		childNode.setLocationX(constraint.x);
		childNode.setLocationY(constraint.y);
		childNode.setWidth(constraint.width);
		childNode.setHeight(constraint.height);
	}

	@Override
	public void redo() {
		execute();
	}

	@Override
	public void undo() {
		this.childNode.setContainer(null);
		this.fatherNode.getSubNodes().remove(this.childNode);

		if (modelCmd != null) {
			modelCmd.undo();
		}
	}
}
